package com.deco.back.controller.ueditor;

import java.io.*;
import java.net.URLDecoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.deco.back.dto.Ueditor;
import com.deco.back.utils.NameMaker;
import com.deco.domain.vo.common.FileUploadInfoVo;
import com.free.common.vo.ResultModel;
import com.free.exception.SystemException;
import com.free.files.FileManagers;
import com.free.files.IFiler;
import com.free.utils.DateUtils;

@RestController
@RequestMapping(value = "/ueditor")
public class UeditorController {
	
    @Value(value = "${sys.img.root}")
    private String fileRoot;

    @Value(value = "${sys.img.uedit.directory}")
    private String fileDirectory;
	
    @Value(value = "${sys.img.domain}")
    private String hostDomain;
    
	  //ueditr后端配置
    @ResponseBody
    @RequestMapping(value = "controller",headers = "Accept=application/json")
    public String ueditor(@RequestParam("action") String action,MultipartFile upfile, String nocache, HttpServletRequest request, HttpServletResponse response){
        try {
            response.setContentType("application/json;charset=utf-8");
            StringBuilder stringBuilder = new StringBuilder();
            if(action.equals("uploadimage")){
            	  ResultModel result = ResultModel.failure();
            	if (!upfile.isEmpty()) {
	       	    	 try {
	       	    		 
	       
	       	    	     StringBuilder fileNamesb = new StringBuilder();
	       	    	     String[] fileNmArr = getOrgFileNameArr(upfile.getOriginalFilename());
	       	    	     fileNamesb.append(NameMaker.getInstance().getStr32()).append(".").append(fileNmArr[1]);
	    	    	     String path = filePath(fileNamesb.toString());
	            	     ResultModel res = FileManagers.getFiler().upload(upfile.getBytes(),path);
	       	    		 
	            
	       	    		 
	       	    		 
//	       	             IFiler filer = FileManagers.getFiler();
//	       	             String destpath = filer.getClass().getClassLoader().getResource("").getPath()+ "static/uploadfiles/test1.jpg";
//	       	             result = filer.upload(upfile.getBytes(), URLDecoder.decode(destpath,"utf-8"));
//	       	             System.out.println(JSON.toJSONString(result));
	       	            Ueditor ueditor = new Ueditor();
		              	ueditor.setOriginal(upfile.getName());
		              	ueditor.setUrl(fileUrl(fileNamesb.toString()));
		              	ueditor.setTitle(upfile.getName());
		              	ueditor.setState("SUCCESS");
		              	
		              	return JSONObject.toJSONString(ueditor);
	
	       	         } catch (SystemException e) {
	       	             e.printStackTrace();
	       	         } catch (UnsupportedEncodingException e) {
	       	             e.printStackTrace();
	       	         } catch (IOException e) {
	       				// TODO Auto-generated catch block
	       				e.printStackTrace();
	       			}
	       	    	
	       	    }
           
            	
            }
            else{
                InputStream stream = getClass().getClassLoader().getResourceAsStream("static/json/ueditorConfig.json");
        	   //Resource resource = new ClassPathResource("static/json/ueditorConfig.json");
               //File file = resource.getFile();
               //BufferedReader br = new BufferedReader(new FileReader(file));
                BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
               String line;
               while ((line = br.readLine()) != null){
                   stringBuilder.append(line);
               }
            }
         
            return stringBuilder.toString();
        }catch (Exception e){
            e.printStackTrace();
            return "error";
        }
        
    }
    
    private String filePath(String fileName){
        StringBuffer strBuf = new StringBuffer();
        return strBuf.append(fileRoot)
                .append(fileDirectory)
                .append(File.separator)
                .append(DateUtils.now(DateUtils.FormatEnum.yyyyMM))
                .append(File.separator)
                .append(fileName).toString();
    }
    
    private String fileUrl(String fileName){
        StringBuffer strBuf = new StringBuffer();
        return strBuf
                .append(fileDirectory)
                .append(File.separator)
                .append(DateUtils.now(DateUtils.FormatEnum.yyyyMM))
                .append(File.separator)
                .append(fileName).toString();
    }
    
    private String[] getOrgFileNameArr(String fileName){
        int n = fileName.lastIndexOf(".");
        return new String[] { fileName.substring(0, n), fileName.substring(n + 1) };
    }
}
